<template>
  <!-- 页面-菜单管理 -->
  <div 
    class="MenuManage-page innerPageTable-out-flex"
    :class="{'innerPageTable-box-OneTwo': !useTableSearchBar}"
    >
    <!-- 搜索区域 -->
    <SelfAdaption v-if="!useTableSearchBar">
      <Form
        :model="searchForm"
        ref="menuSearchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 功能组编码 -->
          <Form-item prop="menuCode" :label="$t('module.menu.menuCode')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.menuCode"
              :placeholder="$t('module.menu.warning.enterMenuCode')"
              @on-enter="search"
            ></Input>
          </Form-item>

          <!-- 功能组名称 -->
          <Form-item prop="menuName" :label="$t('module.menu.menuName')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.menuName"
              :placeholder="$t('module.menu.warning.enterMenuName')"
              @on-enter="search"
            ></Input>
          </Form-item>

          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="menuTable" :config="tableConfig">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="add" />
        <RPButton optType="batch" @click="deleted" />
      </div>
      <Form
        :model="searchForm"
        v-if="useTableSearchBar"
        ref="menuSearchForm"
        slot="table-search-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- 功能组编码 -->
          <Form-item prop="menuCode">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.menuCode"
              :placeholder="$t('module.menu.warning.enterMenuCode')"
              clearable
              @on-enter="search"
              @on-blur="search"
              @on-clear="search"
            ></Input>
          </Form-item>

          <!-- 功能组名称 -->
          <Form-item prop="menuName">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.menuName"
              :placeholder="$t('module.menu.warning.enterMenuName')"
              clearable
              @on-enter="search"
              @on-blur="search"
              @on-clear="search"
            ></Input>
          </Form-item>
        </template>
      </Form>
    </InnerPageTable>
  </div>
</template>
<style lang="less"></style>
<script>
import menuAPI from '@/api/menuAPI.js'
import { menuColumns } from './columns.js'
import MenuEdit from './MenuEdit.vue'
import PermissionEdit from './PermissionEdit.vue'
import MenuShowDetail from './MenuShowDetail.vue'
import locales from './locales.js'
import { CoreModuleName } from '@/const.js'
import valueSetAPI from '@/api/valueSetAPI.js'
import roleApi from '@/api/roleApi.js'

export default {
  name: 'menu-manage',
  mixins: [locales],
  data() {
    return {
      userInfo: {},
      searchForm: {
        tenantCode: '',
        menuName: '',
        menuCode: ''
      },
      menuTypeList: {}
    }
  },
  computed: {
    tableConfig() {
      return { loadDataFn: this.queryMenuList, columnsFn: menuColumns.bind(this), autoFirst: false }
    }
  },
  created: function() {
    this.init()
  },
  mounted() {},
  methods: {
    init() {
      let { userInfo } = $store.state[CoreModuleName]
      if (!userInfo) return
      // 当前租户Id
      this.userId = userInfo.id
      // 当前租户
      this.searchForm.tenantCode = userInfo.tenantCode

      // 初始化菜单类型
      this.initMenuType()
    },
    // 初始化菜单类型
    initMenuType() {
      valueSetAPI.getValueSetByCode('SYS_MENU_TYPE').then(data => {
        for (const menuType of data) {
          this.menuTypeList[menuType.vsiKey] = menuType.vsiValue
        }
        this.search()
      })
    },
    search(page = 1) {
      this.$refs['menuTable'].load(this.searchForm, page)
    },
    reset() {
      this.$refs['menuSearchForm'].resetFields()
      this.search(1)
    },
    getOperations(menu) {
      let operations = []
      if (menu.isThirdAuth == 1) {
        operations = [
          {
            type: 'icon',
            icon: 'ios-eye',
            text: this.$t('common.detail'),
            handle: () => {
              this.showDetail(menu.id, menu)
            }
          }
        ]
      } else {
        operations = [
          {
            type: 'icon',
            icon: 'md-create',
            text: this.$t('common.edit'),
            handle: () => {
              this.edit(menu.id, menu)
            }
          },
          {
            type: 'icon',
            icon: 'ios-settings',
            text: this.$t('module.menu.permissionMaList'),
            handle: () => {
              this.editPermisson(menu)
            }
          },
          {
            type: 'icon',
            icon: 'ios-trash',
            text: this.$t('common.delete'),
            hidden: menu.enabled == 1,
            handle: () => {
              this.deleted(menu)
            }
          }
        ]
      }

      return operations
    },
    // 查看详情
    showDetail(id, menu) {
      new this.$pageModal(
        MenuShowDetail,
        {
          props: {
            menuId: id,
            tenantCode: this.searchForm.tenantCode,
            rowList: menu
          }
        },
        data => {
          // data && this.search();
        }
      )
    },
    edit(id, menu) {
      new this.$pageModal(
        MenuEdit,
        {
          props: {
            menuId: id,
            tenantCode: this.searchForm.tenantCode,
            rowList: menu.id ? menu : {}
          }
        },
        data => {
          data && this.search(this.$refs.menuTable.param.pageNum)
        }
      )
    },
    editPermisson(menu) {
      new this.$pageModal(
        PermissionEdit,
        {
          props: {
            menuId: menu.id
          }
        },
        data => {}
      )
    },
    add() {
      new this.$pageModal(
        MenuEdit,
        {
          props: {
            tenantCode: this.searchForm.tenantCode
          }
        },
        data => {
          data && this.search()
        }
      )
    },
    async deleted(menu) {
      let selectedIds
      let selectedMenus
      if (menu && typeof menu.id == 'string') {
        selectedIds = [menu.id]
        selectedMenus = [menu]
      } else {
        selectedIds = this.getSelectedIds()
        selectedMenus = this.$refs['menuTable'].getSelectioned()
        if (selectedIds.length == 0) {
          this.$message.error({
            content: this.$t('module.menu.warning.selectMenu')
          })
          return
        }
      }
      // 处理删除提示内容
      let deleteTip
      let deleteTipRole = ''
      for (let item of selectedMenus) {
        await roleApi.getRoleByMenu({ menuIds: [item.id] }).then(res => {
          item.roleByMenu = res.map(i => {
            return i.roleName
          })
          // 批量删除才需列出各功能组对应的角色
          if (selectedMenus.length > 1 && item.roleByMenu && item.roleByMenu.length) {
            deleteTipRole += '[' + item.menuName + ':' + item.roleByMenu + ']' + '\n'
          }
        })
      }
      // 删除提示：批量删除与单个删除需显示对应删除提示内容格式，否则显示默认提示。
      deleteTip =
        selectedMenus.length > 1 && deleteTipRole
          ? [
              this.$t('module.menu.warning.confirmDelete') + '\n' + this.$t('module.menu.warning.influenceRole') + ':',
              deleteTipRole
            ]
          : selectedMenus.length == 1 && selectedMenus[0].roleByMenu.length != 0
          ? [
              this.$t('module.menu.warning.confirmDelete'),
              this.$t('module.menu.warning.influenceRole') + ':' + selectedMenus[0].roleByMenu
            ]
          : this.$t('module.menu.warning.ensureToDelete')

      // 数组则代表显示严重提示，字符串则为显示普通提示
      if (Array.isArray(deleteTip)) {
        this.$confirm.swarning(deleteTip).then(() => {
          this.deletedAction(selectedIds)
        })
      } else {
        new $confirm(deleteTip, this).then(() => {
          this.deletedAction(selectedIds)
        })
      }
    },
    deletedAction(selectedIds) {
      menuAPI
        .deleteMenu(selectedIds)
        .then(res => {
          this.$message.success({
            content: this.$t('common.deleteSuccess'),
            duration: 3
          })
          this.search()
        })
        .catch(data => {
          this.$message.error({
            content: data.message,
            duration: 3
          })
        })
    },
    // deleted(id) {
    //   let selectedIds;
    //   if (id) {
    //     selectedIds = [id];
    //   } else {
    //     selectedIds = this.getSelectedIds();
    //     if (selectedIds.length == 0) {
    //       this.$message.error({
    //         content: this.$t("module.menu.warning.selectMenu")
    //       });
    //       return;
    //     }
    //   }
    //   // let selectedIds = this.getSelectedIds();
    //   // if (selectedIds.length == 0) {
    //   //   this.$message.error({
    //   //     content: this.$t("module.menu.warning.selectMenu")
    //   //   });
    //   //   return;
    //   // }
    //   new $confirm(this.$t("module.menu.warning.ensureToDelete"), this).then(() => {
    //     menuAPI
    //       .deleteMenu(selectedIds)
    //       .then(res => {
    //         this.$message.success({
    //           content: this.$t("common.deleteSuccess"),
    //           duration: 3
    //         });
    //         this.search();
    //       })
    //       .catch(data => {
    //         this.$message.error({
    //           content: data.message,
    //           duration: 3
    //         });
    //       });
    //   });
    // },
    getSelectedIds() {
      let list = this.$refs['menuTable'].getSelectioned() || []
      let ids = []
      for (let u of list) {
        ids.push(u.id)
      }
      return ids
    },
    getDateString(DateStr) {
      if (DateStr == undefined || DateStr == null || DateStr == '' || DateStr.trim() == '') {
        return ''
      }
      // return DateStr.split(" ")[0];
      let dateList = DateStr.split(' ')[0].split('-')
      let newDateList = []
      let newItem = ''
      for (let key = 0; key < dateList.length; key++) {
        let newNummber = parseInt(dateList[key])
        if (newNummber < 10) {
          newNummber = '0' + newNummber
        }
        newDateList.push(newNummber)
      }
      return newDateList.join('-')
    },
    // 获取菜单列表数据
    queryMenuList({ responseProcess, param }) {
      menuAPI.queryMenuList(param).then(data => {
        // 状态为有效：禁用复选框，不可删除
        let { records } = data
        records = this.$root.$options.filters['selection-disabled'](records)
        responseProcess(data)
      })
    }
  }
}
</script>
<style lang="less">
.MenuManage-page {
  .ivu-table {
    .ivu-table-fixed-right {
      .ivu-table-fixed-body {
        .ivu-table-tbody {
          tr {
            .ivu-table-cell {
              width: 109px !important;
            }
          }
        }
      }
    }
  }
}
</style>
